package com.senmiao.ssm.controller;

import com.senmiao.ssm.aspect.annotation.DoLoginLog;
import com.senmiao.ssm.aspect.annotation.DoLogoutLog;
import com.senmiao.ssm.pojo.AdminShiro;
import com.senmiao.ssm.service.CommonService;
import com.senmiao.ssm.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class CommonController {

    @Autowired
    private CommonService commonService;

    /**
     * 登录
     * @param account
     * @param password
     * @return
     */
    @DoLoginLog
    @RequestMapping("/admin/login")
    public Result login(String account,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        subject.login(token);
        // 获取登录者的角色对应的访问页面
        AdminShiro principal = (AdminShiro) subject.getPrincipal();
        String url = commonService.getForwardUrlByAdminId(principal.getId());
        return Result.ok().data("url",url);
    }

    /**
     * 登出
     * @return
     */
    @DoLogoutLog
//    @RequiresPermissions("/admin/logout:get")
    @GetMapping("/admin/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }

    /**
     * 获取当前登录的管理员的信息
     * @return
     */
    @RequiresPermissions("/admin/info/get:get")
    @GetMapping("/admin/info/get")
    public Result getAdminInfo(){
        Subject subject = SecurityUtils.getSubject();
        AdminShiro adminShiro = (AdminShiro) subject.getPrincipal();
        return commonService.getAdminInfo(adminShiro.getId());
    }

    /**
     * 修改密码
     * @param currentPassword
     * @param newPassword
     * @return
     */
    @RequiresPermissions("/admin/password/update:post")
    @RequestMapping("/admin/password/update")
    public Result updatePassword(String currentPassword,String newPassword){
        AdminShiro principal = (AdminShiro) SecurityUtils.getSubject().getPrincipal();
        return commonService.updatePassword(principal.getId(),currentPassword,newPassword);
    }

    /**
     * 修改当前登录的管理员信息
     * @param username
     * @param phone
     * @param email
     * @return
     */
    @RequiresPermissions("/admin/info/update:post")
    @RequestMapping("/admin/info/update")
    public Result updateInfo(String username,String phone,String email){
        AdminShiro principal = (AdminShiro) SecurityUtils.getSubject().getPrincipal();
        return commonService.updateInfo(principal.getId(),username,phone,email);
    }

}